<?php

namespace app\api\controller\shop;


use app\admin\model\Cmdlog;
use app\admin\model\Org;
use app\admin\model\Shopcharge;
use app\admin\model\Shopdevice;
use app\admin\model\Shopdou;
use app\admin\model\Shopmeituan;
use app\admin\model\Shopmno;
use app\admin\model\Shoporder;
use app\admin\model\Shoporderprofit;
use app\admin\model\Shoproom;
use app\admin\model\Shoproomset;
use app\admin\model\Shopstaff;
use app\admin\model\Shoptableorder;
use app\admin\model\Shoptableset;
use app\admin\model\Useragent;
use app\admin\model\Userbalance;
use app\admin\model\Usercard;
use app\admin\model\Userdoucode;
use app\admin\model\Usermeituancode;
use app\admin\model\Userwithdraw;
use app\api\service\AirService;
use app\api\service\BalanceService;
use app\api\service\BankService;
use app\api\service\CommonService;
use app\api\service\TableService;
use app\api\service\VbillService;
use app\common\controller\Api;
use fast\Http;
use OSS\OssClient;

/**
 *
 */
class Shoptable extends Api
{
    protected $noNeedLogin = [];
    protected $noNeedRight = ['*'];


    //添加台桌
    public function add(){

        $name = $this->request->param('name');
        $shop_id = $this->request->param('shop_id');
        $min_pay = $this->request->param('min_pay');
        $ya_amount = $this->request->param('ya_amount');
        $logo = $this->request->param('logo');
        $time1 = $this->request->param('time1');
        $price1 = $this->request->param('price1');
        $time2 = $this->request->param('time2');
        $price2 = $this->request->param('price2');
        $id = $this->request->param('id');
        $weigh = $this->request->param('weigh');
        if(!$weigh) $weigh = 1;



        $db = array();
        $db['name'] = $name;
        $db['logo'] = $logo;
        $db['ya_amount'] = $ya_amount;
        $db['min_amount'] = $min_pay;
        $db['shop_id'] = $shop_id;
        $db['weigh'] = $weigh;

        $obj = array();
        $obj['time1'] = $time1;
        $obj['price1'] = $price1;
        $obj['time2'] = $time2;
        $obj['price2'] = $price2;
        $db['rule'] = json_encode($obj);

        $shopTableModel = new \app\admin\model\Shoptable();
        if($id != ""){
            $shopTableModel->where('id',$id)->update($db);
        }else{
            $shopTableModel->insert($db);
        }
        $this->success('成功');

    }


    //获取台桌列表
    public function getList(){

        $shop_id = $this->request->param('shop_id');
        $shopTableModel = new \app\admin\model\Shoptable();
        $list = $shopTableModel->where('shop_id',$shop_id)->order('id','asc')->select();


        $shopDeviceModel = new Shopdevice();


        foreach ($list as $key=>$val){

            $device = $shopDeviceModel->where('shop_id',$val['shop_id'])->where('room_id',$val['id'])->where('device_type','tq')->find();
            if($device) {
                $list[$key]['bind'] = 1;
            }else {
                $list[$key]['bind'] = -1;

            }

            $list[$key]['logo'] = cdnurl($val['logo'],true);
            $rule = json_decode($val['rule'],true);
            $list[$key]['rule'] = $rule;

            $list[$key]['check'] = true;

        }

        $this->success('',$list);
    }

    //绑定设备
    public function bindDevice(){

        $sn = $this->request->param('sn');
        $shop_id = $this->request->param('shop_id');
        $room_id = $this->request->param('room_id');

        $user = $this->auth->getUser();
        $deviceModel = new Shopdevice();

        $shopModel = new \app\admin\model\Shop();
        $shop = $shopModel->where('id',$shop_id)->where('user_id',$user['id'])->find();

        error_log("==d==".json_encode($shop));
        if(!$shop) $this->error("无权限操作");

        $d = $deviceModel->where('device_sn',$sn)->find();

        if($d['user_id'] != $user['id']){
            $this->error("无权限操作");
        }
        if($d['bind_status'] != -1){
            $this->error("先解绑再操作");
        }

        $deviceModel->where('id',$d['id'])->update(['shop_id'=>$shop_id,'room_id'=>$room_id,'bind_status'=>1]);

        $this->success('');
    }

    //台桌详情
    public function detail(){

        $id = $this->request->param('id');
        $shopTableModel = new \app\admin\model\Shoptable();
        $shopModel = new \app\admin\model\Shop();
        $table = $shopTableModel->where('id',$id)->find();
        $shop = $shopModel->where('id',$table['shop_id'])->find();
        $table['logo_path'] = $table['logo'];
        $table['logo'] = cdnurl($table['logo'],true);

        $table['rule'] = json_decode($table['rule'],true);
        $table['shopName'] = $shop['name'];

        $this->success('',$table);
    }

    //订单列表
    public function getOrderList(){

        $page = $this->request->param('page');
        $shop_id = $this->request->param('shop_id');

        $status = $this->request->param('status');
        $orderNo = $this->request->param('orderNo');
        $startTime = $this->request->param('startTime');


        $shopOrderModel = new Shoptableorder();

        $limit = 10;
        $offset = ($page - 1) * $limit;

        $where = array();
        $where['shop_id'] = $shop_id;
        if($status != ''){
            $where['Shoptableorder.status'] = array('=',$status);
        }
        if($orderNo != ""){
            $where['order_no'] =array('like', "%" . $orderNo . "%");
        }
        if($startTime != "" && $startTime != "时间选择" ){
            $start = strtotime($startTime." 00:00");
            $end = strtotime($startTime." 23:59");
            $where['create_time'] = array("between",array($start,$end));
        }

        $list =  $shopOrderModel->with(['user'])->where('Shoptableorder.status',"<>",'paying')->where($where)->order('create_time','desc')->limit($offset,$limit)->select();
        foreach ($list as $key=>$val){

            $val['user']->hidden(['password', 'salt']);
            $list[$key]['order_no_str'] = substr($val['order_no'],0,5)."*****".substr($val['order_no'],strlen($val['order_no'])-4,4);

            $list[$key]['book_start'] = date("Y-m-d H:i",$val['book_start']);
            $list[$key]['book_end'] = date("Y-m-d H:i",$val['book_end']);
            $list[$key]['create_time_txt'] = date("Y-m-d H:i",$val['create_time']);

            $list[$key]['status_txt'] = $shopOrderModel->formatStatus($val['status']);
        }
        $this->success('',$list);

    }


    //结束订单
    public function overOrder(){

        $user = $this->auth->getUser();
        $order_no = $this->request->param('order_no');
        $tableOrderModel = new Shoptableorder();
        $order = $tableOrderModel->where('order_no',$order_no)->find();
        $from = $this->request->param('from');

        if($order['status'] == 'done'){

            $this->error("此订单此完成 无需操作");
        }
        $deviceModel = new Shopdevice();
        $device = $deviceModel->where('shop_id',$order['shop_id'])->where('room_id',$order['table_id'])->where('device_type','tq')->find();

        if($order['book_end'] == -1){
            if($from != 'task'){
                if(($order['is_qiu']== -1 || $order['is_lock'] == -1) && $device['is_weight'] == 1 ){

                    $this->error("","","2");
                }
            }
            $tableModel = new \app\admin\model\Shoptable();
            $table = $tableModel->where('id',$order['table_id'])->find();
            $shopModel = new \app\admin\model\Shop();
            $shop = $shopModel->where('id',$order['shop_id'])->find();
            $rule = json_decode($table['rule'],true);
            $book_end = time();
            $minute=floor(($book_end-$order['book_start'])%86400/60);
            $hour = ceil($minute/60);
            $start =  date("H",$order['book_start']);


            $time1List = explode("~",$rule['time1']);
            if(count($time1List) == 1){
                $startTime1 = explode("-",$rule['time1'])[0];
                $endTime1 = explode("-",$rule['time1'])[1];
            }else{
                $startTime1 = explode("~",$rule['time1'])[0];
                $endTime1 = explode("~",$rule['time1'])[1];
            }


            $time2List = explode("~",$rule['time2']);
            if(count($time2List) == 1){
                $startTime2 = explode("-",$rule['time2'])[0];
                $endTime2 = explode("-",$rule['time2'])[1];
            }else{
                $startTime2 = explode("~",$rule['time2'])[0];
                $endTime2 = explode("~",$rule['time2'])[1];
            }
            $startTime1 = intval($startTime1);
            $endTime1 = intval($endTime1);


            $startTime2 = intval($startTime2);
            $endTime2 = intval($endTime2);
            $slots = array();

            if($endTime1 <$startTime1){
                $obj = array();
                $obj['begin'] = $startTime1;
                $obj['end'] = 24;
                $obj['charge'] = $rule['price1'];
                $slots[] = $obj;
                $obj = array();
                $obj['begin'] = 0;
                $obj['end'] = $endTime1;
                $obj['charge'] = $rule['price1'];
                $slots[] = $obj;

            }else{
                $obj = array();
                $obj['begin'] = $startTime1;
                $obj['end'] = $endTime1;
                $obj['charge'] = $rule['price1'];
                $slots[] = $obj;
            }

            if($endTime2 <$startTime2){
                $obj = array();
                $obj['begin'] = $startTime2;
                $obj['end'] = 24;
                $obj['charge'] = $rule['price2'];
                $slots[] = $obj;
                $obj = array();
                $obj['begin'] = 0;
                $obj['end'] = $endTime2;
                $obj['charge'] = $rule['price2'];
                $slots[] = $obj;

            }else{
                $obj = array();
                $obj['begin'] = $startTime2;
                $obj['end'] = $endTime2;
                $obj['charge'] = $rule['price2'];
                $slots[] = $obj;
            }

            $hour = floor($minute/60);

            $orderAmount = $order['pay_amount'];
            $pay_amount = 0;
            if($order['mt_code'] != '' || $order['dou_code'] != '' || $order['tuan_id'] != -1){

                $orderAmount = 0;
                $amount = $order['amount'];
                $pay_amount =0;
            }else{
                $amount = get_charge($start,$hour,$slots,$minute);
                if($amount <= $table['min_amount']){
                    $amount = $table['min_amount'];

                }

                if($amount > $order['ya_amount'] && $order['pay_amount']>0){
                    $amount = $order['ya_amount'];//先暂时这样处理
                }
                $orderAmount = $amount;

            }

            //1.计算费用
            $tableModel->where('id',$order['table_id'])->update(['status'=>'free']);
            //2.断电

            $mno= $this->mno;
            $refundAmount = 0;
            $dbBalance = 0;


            if($orderAmount >0){

                $userBalanceModel = new Userbalance();

                //如果是余额开台
                if($order['balance'] >0 && $order['ya_amount'] == 0){
                    $pay_amount =0;
                    $refundAmount = 0;
                    $dbBalance = $amount;
                    $b = $userBalanceModel->where('order_id',$order['id'])->where('from','tq')->find();
                    if($b){
                        $userBalanceModel->where('id',$b['id'])->update(['amount'=>$dbBalance]);
                    }
                }else{
                    $balance  = $userBalanceModel->balance($order['shop_id'],$order['user_id']);
                    if($balance <0) $balance = 0;
                    $shopOrderProfitModel = new Shoporderprofit();
                    if($balance ==0){
                        //3. 发分润
                        $pay_rate = formatMoney($shop['pay_rate'] *$amount / 100);
                        $rate = formatMoney($shop['ratio'] * $amount / 100);
                        $shopProfit = $amount-$pay_rate-$rate;
                        $refundAmount = $order['ya_amount']-$amount;
                        $pay_amount = $amount;
                        $dbBalance = 0;
                        $shopOrderProfitModel->insert(['order_id' => $order['id'], 'shop_id' => $order['shop_id'], 'type' => 'order',
                            'user_id' => $shop['user_id'], 'create_time' => time(),'from'=>'tq', 'amount' => formatMoney($shopProfit)]);
                    }else{

                        if($amount <= $balance){
                            $refundAmount = $order['ya_amount'];
                            $dbBalance = $amount;
                            $pay_amount = 0;
                            error_log("===amount=====".$amount);
                        }else{
                            $refundAmount = $order['ya_amount'] -($amount-$balance);
                            $dbBalance = $balance;
                            $dbAmount = $amount-$balance;
                            $pay_amount = $order['ya_amount']-$refundAmount;

                            $pay_rate = formatMoney($shop['pay_rate'] *$dbAmount / 100);
                            $rate = formatMoney($shop['ratio'] * $dbAmount / 100);
                            $shopProfit = $amount-$pay_rate-$rate;

                            if($shopProfit >0){
                                $shopOrderProfitModel->insert(['order_id' => $order['id'], 'shop_id' => $order['shop_id'], 'type' => 'order',
                                    'user_id' => $shop['user_id'], 'create_time' => time(),'from'=>'tq', 'amount' => formatMoney($shopProfit)]);
                            }

                        }
                        if($dbBalance >0){
                            $userBalanceModel->insert(['user_id'=>$order['user_id'],'type'=>'out','amount'=>$dbBalance,'mark'=>'台球抵扣','create_time'=>time(),'shop_id'=>$order['shop_id'],'order_id'=>$order['id'],'b_type'=>'order','from'=>'tq']);
                        }
                    }
                    //部分退款
                    $shopMnoModel = new Shopmno();
                    $shopMno = $shopMnoModel->where('shop_id',$order['shop_id'])->find();
                    if($shopMno && $shopMno['ratio'] == 100){
                        $mno = $shopMno['mno'];
                    }
                    error_log(formatMoney($refundAmount)."=====refundAmount==".$refundAmount);

                    $req = array();
                    $req['mno']=$mno;
                    $req['ordNo']= getOrderSn();
                    $req['origOrderNo']= $order['order_no'];
                    $req['amt']= formatMoney($refundAmount);

                    if($refundAmount >0) {
                        error_log("==refund req===" . json_encode($req));
                        $vbillService = new VbillService();
                        $ret = $vbillService->refund($req);
                        error_log("=====refund=sxf==" . $ret);
                    }
                }


            }else{
                //扣余额

                if($order['dou_code'] != '' || $order['mt_code'] != ""){

                }else{
                    $userBalanceModel = new Userbalance();
                    $db = array();
                    $db['user_id'] = $order['user_id'];
                    $db['type'] = "out";
                    $db['amount'] = $amount;
                    $db['mark'] = $order['shop_name'].$order['table_name']."抵扣";
                    $db['create_time'] =time();
                    $db['shop_id'] = $order['shop_id'];
                    $db['order_id'] = $order['id'];
                    $db['b_type'] = "order";
                    $db['from'] = "tq";
                    $userBalanceModel->insert($db);

                }

            }
            $tableOrderModel->where('id',$order['id'])->update(['book_end'=>$book_end,'amount'=>$amount,'pay_amount'=>$pay_amount,'status'=>'done','refund_amount'=>$refundAmount,'is_done'=>1,'update_time'=>time(),'balance'=>$dbBalance]);
            //关闭
            $tableOrderModel->where('id',$order['id'])->update(['update_time'=>time()]);
        }

        $tableOrderModel->where('id',$order['id'])->update(['status'=>'done']);


        if($device['version'] == 1){
            $req = array();
            $req['switchOne'] = 0;
            $req['switchTwo'] = 0;
            $req['door'] = 2;
            $req['hello'] = "欢迎下次来玩";
            $req['orderNo'] = $order['order_no'];
            $req['sn'] = $device['sn'];

            $ret = http_post_json($this->openTqCmdUrl, json_encode($req));
            $ret = json_decode($ret, true);
        }else if($device['version'] == 2){
            $req['sec'] = 0;
            $req['voice'] = "欢迎下次来玩";
            $req['orderNo'] = $order['order_no'];
            $req['sn'] = $device['sn'];
            $ret = http_post_json($this->openCmdUrl, json_encode($req));
            $ret = json_decode($ret, true);
        }else if($device['version'] == 3){
            $req  = array();
            $req['sec'] = 0;
            $req['orderId'] = $order['id'];
            $req['deviceSn'] = $device['device_sn'];
            $ret =  http_post_json($this->tqV3CmdUrl,json_encode($req));
            $ret = json_decode($ret,true);
        }


        $cmdModel = new Cmdlog();
        $cmdModel->insert(['user_id' => $order['user_id'], 'order_no' => $order['order_no'], 'cmd' => json_encode($req), 'create_time' => time(), 'shop_id' => $order['shop_id'], 'room_id' => $order['table_id']]);

        $airService = new AirService();
        $airService->airCheck2($order['shop_id'],0);
        $airService->airCheckV2($order['shop_id'],$order['table_id']);
        $this->success('成功');

    }

    //更改台桌
    public function updateOrderTable(){

        $tableOrderModel = new Shoptableorder();
        $order_no = $this->request->param('order_no');
        $id = $this->request->param('id');
        $order = $tableOrderModel->where('order_no',$order_no)->find();
        if($order['table_id'] == $id){
            $this->error("当前台桌和订单台桌一致,无需更改");
        }
        if($order['status'] != "doing"){
            $this->error("当前订单状态不允许更改");
        }
        $shopTableModel = new \app\admin\model\Shoptable();
        $table = $shopTableModel->where('id',$id)->find();
        if($table['status'] == 'busy'){
            $this->error("此台桌正在开台中，不支持更改");
        }
        $tableOrderModel->where('id',$order['id'])->update(['table_id'=>$id,'table_name'=>$table['name']]);

        $deviceModel = new Shopdevice();
        $device = $deviceModel->where('shop_id',$order['shop_id'])->where('room_id',$order['table_id'])->where('device_type','tq')->find();


        $tableService = new TableService();
        $tableService->close($order,$device);

        //开新的台桌，通过查询更新后的订单，查询新的台桌Id
        $order = $tableOrderModel->where('order_no',$order_no)->find();
        $device = $deviceModel->where('shop_id',$order['shop_id'])->where('room_id',$order['table_id'])->where('device_type','tq')->find();
        $tableService->open($order,$device);

        $airService = new AirService();
        $airService->airCheck($order['shop_id']);
        $airService->airCheckV2($order['shop_id'],$order['table_id']);


        $this->success('成功');

    }


    public function getTableCodeUrl(){

        $table_id = $this->request->param('table_id');

        $tableModel = new \app\admin\model\Shoptable();
        $table = $tableModel->where('id',$table_id)->find();

        $shopModel = new \app\admin\model\Shop();
        $shop = $shopModel->where('id',$table['shop_id'])->find();

        $orgModel = new Org();
        $org = $orgModel->where('id',$shop['org_id'])->find();

        $app_id = $org['app_id'];
        $app_secret = $org['app_secret'];


        $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=".$app_id."&secret=".$app_secret;
        $ret = Http::get($url);
        $obj = json_decode($ret, true);
        $token = $obj['access_token'];



        $scene = $shop['id']."-".$table_id;

        $url2 = "https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=$token";
        $data = [
            'scene' => $scene,
            'page' => 'pages/order/ballSubmit',

        ];
        $name = "table_".$shop['id']."_".$table_id;

        $data = json_encode($data);
        //拿到二维码
        $result = Http::post($url2, $data);

        $base64 = base64_encode($result);
        $mime = "image/png";
        $img = 'data:' . $mime . ';base64,' . $base64;
        $filename = './uploads/' . $name . '.jpg';

        $qrcodePath = ROOT_PATH . 'public/uploads/qrcode/';
        if (!is_dir($qrcodePath)) {
            @mkdir($qrcodePath);
        }

        $qrcodePath = ROOT_PATH . 'public/uploads/qrcode/';
        if (!is_dir($qrcodePath)) {
            @mkdir($qrcodePath);
        }
        if (is_really_writable($qrcodePath)) {

            if($table['qr_code'] != ''){

                $url = cdnurl($table['qr_code'],true);
            }else{

                base64_image_content($img, $filename);

                $per = 0.5;
                list($width, $height) = getimagesize($filename);
                $n_w = $width * $per;
                $n_h = $height * $per;
                $new = imagecreatetruecolor($n_w, $n_h);
                $img = imagecreatefromjpeg($filename);
//拷贝部分图像并调整
                imagecopyresized($new, $img, 0, 0, 0, 0, $n_w, $n_h, $width, $height);
//图像输出新图片、另存为
                imagedestroy($new);
                imagedestroy($img);

                $config = get_addon_config('alioss');
                $oss = new OssClient($config['accessKeyId'], $config['accessKeySecret'], $config['endpoint']);
                $ret = $oss->uploadFile($config['bucket'], $name . ".jpg", $filename);
                $url = $ret['info']['url'];

                $tableModel->where('id',$table_id)->update(['qr_code'=>"/".$name.".jpg"]);
                error_log("==oss=ret==".json_encode($ret));

            }


            $this->success('',$url);
        }

    }


    public function getTableBookCodeUrl(){

        $table_id = $this->request->param('table_id');

        $tableModel = new \app\admin\model\Shoptable();
        $table = $tableModel->where('id',$table_id)->find();

        $shopModel = new \app\admin\model\Shop();
        $shop = $shopModel->where('id',$table['shop_id'])->find();

        $orgModel = new Org();
        $org = $orgModel->where('id',$shop['org_id'])->find();

        $app_id = $org['app_id'];
        $app_secret = $org['app_secret'];


        $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=".$app_id."&secret=".$app_secret;
        $ret = Http::get($url);
        $obj = json_decode($ret, true);
        $token = $obj['access_token'];



        $scene = $shop['id']."-".$table_id;

        $url2 = "https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=$token";
        $data = [
            'scene' => $scene,
            'page' => 'pages/order/tableSubmit',

        ];
        $name = "table_book_".$shop['id']."_".$table_id;

        $data = json_encode($data);
        //拿到二维码
        $result = Http::post($url2, $data);

        $base64 = base64_encode($result);
        $mime = "image/png";
        $img = 'data:' . $mime . ';base64,' . $base64;
        $filename = './uploads/' . $name . '.jpg';

        $qrcodePath = ROOT_PATH . 'public/uploads/qrcode/';
        if (!is_dir($qrcodePath)) {
            @mkdir($qrcodePath);
        }

        $qrcodePath = ROOT_PATH . 'public/uploads/qrcode/';
        if (!is_dir($qrcodePath)) {
            @mkdir($qrcodePath);
        }
        if (is_really_writable($qrcodePath)) {

            if($table['book_qr_code'] != ''){

                $url = cdnurl($table['book_qr_code'],true);
            }else{

                base64_image_content($img, $filename);

                $per = 0.5;
                list($width, $height) = getimagesize($filename);
                $n_w = $width * $per;
                $n_h = $height * $per;
                $new = imagecreatetruecolor($n_w, $n_h);
                $img = imagecreatefromjpeg($filename);
//拷贝部分图像并调整
                imagecopyresized($new, $img, 0, 0, 0, 0, $n_w, $n_h, $width, $height);
//图像输出新图片、另存为
                imagedestroy($new);
                imagedestroy($img);

                $config = get_addon_config('alioss');
                $oss = new OssClient($config['accessKeyId'], $config['accessKeySecret'], $config['endpoint']);
                $ret = $oss->uploadFile($config['bucket'], $name . ".jpg", $filename);
                $url = $ret['info']['url'];

                $tableModel->where('id',$table_id)->update(['book_qr_code'=>"/".$name.".jpg"]);
                error_log("==oss=ret==".json_encode($ret));

            }


            $this->success('',$url);
        }

    }



    public function orderDetail(){

        $order_no = $this->request->param('order_no');
        $tableOrderModel = new Shoptableorder();
        $table = $tableOrderModel->with(['user'])->where('order_no',$order_no)->find();

        $userBalanceModel = new Userbalance();
        $balance = $userBalanceModel->where('order_id',$table['id'])->where('from','tq')->find();
        if($table['status']=='doing'){
            $table['status_txt'] = "进行中";
        }else if($table['status'] == 'done'){
            $table['status_txt'] = "已完成";
        }else if($table['status'] == 'refund'){
            $table['status_txt'] = "已退款";
        }
        $table['create_time_text'] = date("Y-m-d H:i",$table['create_time']);
        $table['book_start'] = date("Y-m-d H:i",$table['book_start']);
        if($table['book_end'] != -1){
            $table['book_end'] = date("Y-m-d H:i",$table['book_end']);
        }else{
            $table['book_end'] = "";
        }
        $table['balance'] = 0;
        $table['dou_name'] = "";
        $table['mt_name'] = "";

        if($balance){
            $table['balance'] = $balance['amount'];
        }
        if($table['dou_code'] != ""){

            $userDoucCodeModel = new Userdoucode();
            $dou = $userDoucCodeModel->where('dou_code',$table['dou_code'])->find();

            $shopDouModel = new Shopdou();
            $shopDou = $shopDouModel->where('sku_id',$dou['sku_id'])->where('shop_id',$dou['shop_id'])->find();
            if($shopDou){
                $table['dou_name'] = $shopDou['sku_name'];
            }
        }
        if($table['mt_code'] != ""){

            $userMtCode = new Usermeituancode();
            $userMt = $userMtCode->where('mt_code',$table['mt_code'])->find();

            $shopMtModel = new Shopmeituan();
            $shopMt = $shopMtModel->where('id',$userMt['group_id'])->find();
            if($shopMt){
                $table['mt_name'] = $shopMt['title'];
            }
        }

        $this->success('',$table);
    }


    public function deleteTable()
    {

        $user = $this->auth->getUser();

        $table_id = $this->request->param('table_id');
        $shopTableModel = new \app\admin\model\Shoptable();
        $table = $shopTableModel->where('id',$table_id)->find();
        if(!$table){
            $this->error("台桌不存在");
        }
        $shopModel = new \app\admin\model\Shop();
        $shop = $shopModel->where('id',$table['shop_id'])->find();
        if($user['id'] != $shop['user_id']) $this->error("没有权限操作");
        $shopTableModel->where('id',$table['id'])->delete();
        $shopDeviceModel = new Shopdevice();
        $shopDeviceModel->where('room_id',$table['id'])->where('device_type','tq')->update(['room_id'=>-1,'bind_status'=>-1]);

        $this->success('成功');
    }


    public function getTableSet()
    {

        $id = $this->request->param('table_id');
        $tableSetModel = new Shoptableset();
        $list = $tableSetModel->where('table_id', $id)->order('hour', 'asc')->select();

        $this->success('', $list);
    }

    public function addTableSetItem()
    {

        $room_id = $this->request->param('id');
        $set = $this->request->param('set');

        $shopRoomModel = new \app\admin\model\Shoptable();
        $shopRoomSetModel = new Shoptableset();
        $room = $shopRoomModel->where('id', $room_id)->find();
        $shop_id = $room['shop_id'];

        $set = json_decode(htmlspecialchars_decode($set), true);

        $db = array();
        foreach ($set as $key => $val) {
            $obj = array();
            //套餐时长不能低于1小时
            if ($val['hour'] < 1) {
                $this->error("套餐的时长不能低于1小时");
            }
            if ($val['id'] == -1) {

                if ($val['hour'] * 6 > $val['amount']) {

                    $this->error("套餐的价格设置过低");
                    break;
                } else {

                    if ($val['name'] != "") {
                        $obj['name'] = $val['name'];
                    } else {
                        $obj['name'] = $val['hour'] . "小时套餐";

                    }
                    $obj['shop_id'] = $shop_id;
                    $obj['table_id'] = $room_id;
                    $obj['hour'] = $val['hour'];
                    $obj['amount'] = $val['amount'];
                    $shopRoomSetModel->insert($obj);
                }

            } else {

                if ($val['hour'] * 6 > $val['amount']) {

                    $this->error("套餐的价格设置过低");
                    break;
                } else {
                    if ($val['name'] != "") {
                        $obj['name'] = $val['name'];
                    } else {
                        $obj['name'] = $val['hour'] . "小时套餐";

                    }
                    $obj['shop_id'] = $shop_id;
                    $obj['table_id'] = $room_id;
                    $obj['hour'] = $val['hour'];
                    $obj['amount'] = $val['amount'];
                    $shopRoomSetModel->where('id', $val['id'])->update($obj);
                }

            }
        }
        $this->success('成功', $set);
    }

    public function removeTableSetItem()
    {
        $user = $this->auth->getUser();
        $id = $this->request->param('id');
        $shopTableSetModel = new Shoptableset();
        $shopModel = new \app\admin\model\Shop();
        $roomSet = $shopTableSetModel->where('id', $id)->find();
        $shop = $shopModel->where('user_id', $user['id'])->where('id', $roomSet['shop_id'])->find();
        if (!$shop) {
            $this->error("无权限操作");
        }
        $shopTableSetModel->where('id', $id)->delete();

        $this->success('移除成功');

    }

    public function addRoomSet()
    {
        $table_id = $this->request->param('id');
        $set = $this->request->param('set');

        $tableModel = new \app\admin\model\Shoptable();
        $tableSetModel = new Shoptableset();
        $table = $tableModel->where('id', $table_id)->find();
        $shop_id = $table['shop_id'];

        $set = json_decode(htmlspecialchars_decode($set), true);

        $db = array();
        foreach ($set as $key => $val) {
            $obj = array();
            //套餐时长不能低于1小时
            if ($val['hour'] < 1) {
                $this->error("套餐的时长不能低于1小时");
            }
            if ($val['id'] == -1) {

                if ($val['hour'] * 6 > $val['amount']) {

                    $this->error("套餐的价格设置过低");
                    break;
                } else {

                    if ($val['name'] != "") {
                        $obj['name'] = $val['name'];
                        $obj['time'] = $val['time'];
                        $obj['end_time'] = $val['end_time'];
                    } else {
                        $obj['name'] = $val['hour'] . "小时套餐";

                    }
                    $obj['shop_id'] = $shop_id;
                    $obj['table_id'] = $table_id;
                    $obj['hour'] = $val['hour'];
                    $obj['amount'] = $val['amount'];
                    $obj['original_amount'] = $val['original_amount'];
                    if (count($val['week']) > 0) {
                        sort($val['week']);
                        $obj['week'] = json_encode($val['week']);
                    } else {
                        $obj['week'] = '[]';
                    }
                    $tableSetModel->insert($obj);
                }

            } else {

                if ($val['hour'] * 6 > $val['amount']) {

                    $this->error("套餐的价格设置过低");
                    break;
                } else {
                    if ($val['time'] == '') {
                        $obj['name'] = $val['hour'] . "小时套餐";
                    } else {
                        $obj['name'] = $val['name'];
                        $obj['time'] = $val['time'];
                        $obj['end_time'] = $val['end_time'];
                    }
                    $obj['shop_id'] = $shop_id;
                    $obj['table_id'] = $table_id;
                    $obj['hour'] = $val['hour'];
                    $obj['amount'] = $val['amount'];
                    $obj['original_amount'] = $val['original_amount'];
                    if (count($val['week']) > 0) {
                        sort($val['week']);
                        $obj['week'] = json_encode($val['week']);
                    } else {
                        $obj['week'] = '[]';
                    }
                    $tableSetModel->where('id', $val['id'])->update($obj);
                }
            }

        }
        $this->success('成功');

    }

    //获取房间套餐
    public function getRoomSet()
    {
        $table_id = $this->request->param('table_id');
        $sale = $this->request->param('sale');
        $tableSetModel = new Shoptableset();
        if ($sale != "") {
            $list = $tableSetModel->where('time', "<>", '')->where('table_id', $table_id)->order('hour', 'asc')->select();
        } else {
            $list = $tableSetModel->where('time', '')->where('table_id', $table_id)->order('hour', 'asc')->select();

        }

        foreach ($list as $key => $v) {
            if (!empty($v['week'])) {
                $list[$key]['week'] = json_decode($v['week'], true);
            }
        }

        $this->success('', $list);
    }

    //复制套餐或者包厢列表（排除当前包厢）
    public function getCopyRoom()
    {
        $table_id = $this->request->param('table_id');

        $tableModel = new \app\admin\model\Shoptable();
        $table = $tableModel->where('id', $table_id)->find();

        $rooms = $tableModel->where('shop_id', $table['shop_id'])->where('id', '<>', $table_id)->select();
        $roomList = array();
        foreach ($rooms as $v) {
            $db = array();
            $db['id'] = $v['id'];
            $db['name'] = $v['name'];

            $roomList[] = $db;
        }
        $this->success('', $roomList);
    }

    public function copyRoomSet()
    {
        $targetRoomIds = $this->request->param('targetRoomIds');
        $setData = $this->request->param('setData');

        $jsonSetData = html_entity_decode($setData);
        $jsonTargetRoomIds = html_entity_decode($targetRoomIds);

        $setData = json_decode($jsonSetData, true);
        $targetRoomIds = json_decode($jsonTargetRoomIds, true);

        $roomSetModel = new Shoptableset();
        $insertDb = array();
        $insertDb['name'] = $setData['name'];
        $insertDb['hour'] = $setData['hour'];
        $insertDb['amount'] = $setData['amount'];
        $insertDb['original_amount'] = $setData['original_amount'];
        $insertDb['shop_id'] = $setData['shop_id'];
        $insertDb['weigh'] = $setData['weigh'];
        $insertDb['time'] = $setData['time'];
        $insertDb['end_time'] = $setData['end_time'];
        $insertDb['week'] = json_encode($setData['week']);

        foreach ($targetRoomIds as $roomIds) {
            $insertDb['table_id'] = $roomIds;

            $roomSetModel->insert($insertDb);
        }

        $this->success('');

    }

}
